package com.sap.apitest2.common;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.MissingResourceException;
import java.util.ResourceBundle;

import org.apache.http.client.ClientProtocolException;

public class APIExecutor {

	private APIDefinition api;
	private String param[];
	private ByteArrayOutputStream response;
	private ByteArrayOutputStream reqStream;
	private int statusCode;
	private final String pkg;
	
	public String getResponseAsString() throws UnsupportedEncodingException {
		if(response!=null) {
			return new String(response.toByteArray(), "utf-8");
		} else {
			return new String();
		}	
	}
	
	public int getStatusCode() {
		return statusCode;
	}

	public APIExecutor(APIDefinition api, String[] param, String request, String pkg) {
		super();
		this.api = api;
		this.param = param;
		this.pkg = pkg;
		if(request!=null) {
		this.reqStream = new ByteArrayOutputStream();
			try {
			
					reqStream.write(request.getBytes());
					reqStream.flush();
					reqStream.close();
				
			} catch (IOException e) {
				throw new IllegalArgumentException(e);
			}
		}
		
	}	
	
	public void execute() throws ClientProtocolException, IOException {
		String uri = api.getURI();
		String[] param2 = api.getParam();
		if(param2!=null) {
			for(int i=0;i<param2.length;i++) {
				uri = uri.replaceAll("<"+param2[i]+">", param[i]);
			}
		}

		HTTPSender httpSender = new HTTPSender(uri, api.getFormat(), api.getMtd(), getBundleName(pkg, ".httprequest"));
		if(reqStream!=null) {
			httpSender.setRequest(reqStream);
		}
		httpSender.send();
		response = httpSender.getResponse();
		statusCode = httpSender.getStatusCode();
	}
	
	
	private String getBundleName(String pkgName, String name) {
		try{
			ResourceBundle.getBundle(pkgName+name);
		}catch (MissingResourceException e) {
			if(pkgName.lastIndexOf(".")!=-1)
				return getBundleName(pkgName.substring(0, pkgName.lastIndexOf(".")), name);
			else
				return null;
		}
		return pkgName+name;
		
	}
}
